package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupMapper checkGroupMapper;



    //新增检查组
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupMapper.add(checkGroup);
        this.setCheckGroupAndCheckItem(checkGroup.getId(), checkitemIds);


    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //修改检查组基本信息  操作检查组 group 表
        checkGroupMapper.edit(checkGroup);
        //清理当前检查组关联的检查项  操作中间关系表
        checkGroupMapper.deleteAssociation1(checkGroup.getId());
        //重新建立当前检查组和检查项的关联关系
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

    }
    //往中间表关联数据---检查组和检查项 多对多
    public void setCheckGroupAndCheckItem(Integer groupId, Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("groupId", groupId);
                map.put("checkitemId", checkitemId);
                checkGroupMapper.setCheckGroupAndCheckItem(map);
            }
        }
    }

    //查询所有
    @Override
    public List<CheckGroup> findAll() {
        List<CheckGroup> checkGroups = checkGroupMapper.findAll();
        return checkGroups;
    }

    //根据ID查询检查组
    @Override
    public CheckGroup findById(Integer id) {

        return checkGroupMapper.findById(id);
    }

    //根据检查组合id查询对应的所有检查项id
    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer groupId) {
        return checkGroupMapper.findCheckItemIdsByCheckGroupId(groupId);
    }



    //查询检查组分页
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page = checkGroupMapper.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void deleteById(Integer id) {


        checkGroupMapper.deleteAssociation1(id);
        checkGroupMapper.deleteAssociation2(id);
        checkGroupMapper.deleteById(id);
    }


}
